package com.huyanqi.core.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FunctionUtils {

	//静态成员的私有构造函数
	private FunctionUtils(){
		throw new AssertionError();
	}
	
	public static String FormatTime(String PATTERN) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(PATTERN);
		Calendar calendar = Calendar.getInstance();
		String time = dateFormat.format(calendar.getTime());
		return time;
	}

	/**
	 * 格式化日期对象
	 * 
	 * @param calendar
	 * @param pattern
	 * @return
	 */
	public static String FormatTime(Calendar calendar, String pattern) {
		return new SimpleDateFormat(pattern).format(calendar.getTime());
	}

	public static String getSuitableImageType(String filename) {
		String[] filetype = Constants.FILE_IMAGE_TYPE;
		if (null == filename || "".equals(filename))
			return null;
		filename = filename.toLowerCase();
		for (String type : filetype) {
			if (filename.endsWith(type)) {
				return type;
			}
		}
		return null;
	}
	public static String getSuitableImageType(String filename,String filetype[]) {
//		String[] filetype = Constants.FILE_IMAGE_TYPE;
		if (null == filename || "".equals(filename))
			return null;
		filename = filename.toLowerCase();
		for (String type : filetype) {
			if (filename.endsWith(type)) {
				return type;
			}
		}
		return null;
	}
	public static String getSuitableArticleType(String filename) {
		String[] filetype = Constants.FILE_ARTICLE_TYPE;
		if (null == filename || "".equals(filename))
			return null;
		filename = filename.toLowerCase();
		for (String type : filetype) {
			if (filename.endsWith(type)) {
				return type;
			}
		}
		return null;
	}
	public static String getConfigFilePath(String pathname) {
		PropertiesUtil propertiesUtil = PropertiesUtil
				.createPropertiesUtil("config.properties");
		return propertiesUtil.getProperty(pathname);
	}

	public static String getURlString(Class<?> classzz, String filename) {
		return classzz.getResource("/" + filename).toString();
	}

	public static Calendar ConvertStringtoCalendar(String strDate,String...pattern)
			throws Exception {
		DateFormat f = null;
		if(null == pattern || pattern.length==0)
			f = new SimpleDateFormat(Constants.DATE_TIME_PATTERN);
		else
			f = new SimpleDateFormat(pattern[0]);
		Calendar cal = Calendar.getInstance();
		cal.setTime(f.parse(strDate));
		return cal;

	}

	public static Calendar ConvertStringtoCalendarDate(String strDate)
			throws Exception {
		DateFormat f = new SimpleDateFormat(Constants.DATE_TIME_DATE_PATTERN);
		Calendar cal = Calendar.getInstance();
		cal.setTime(f.parse(strDate));
		return cal;

	}

	public static String getFileNameFromPath(String Path) {
		if (null == Path || "".equals(Path))
			return null;
		return Path.substring(Path.lastIndexOf("/") + 1);
	}

	/**
	 * 转义页面元素 不能轻易用，考虑保存 \" to &quot;
	 * 
	 * @param source
	 * @return String
	 */
	public static String HTMLChange(String source) {
		String changeStr = source;
		// changeStr=source.replaceAll("&","&amp;");
		// changeStr=changeStr.replaceAll(" ","&nbsp;"); //不能轻易使用，出错。
		// changeStr=changeStr.replaceAll("<","&lt;");
		// changeStr=changeStr.replaceAll(">","&gt;");
		// changeStr=changeStr.replaceAll("\r\n","###");
		changeStr = changeStr.replaceAll("\"", "&quot;");
		changeStr = changeStr.replaceAll("\'", "&#039;");
		// 单引号会有问题
		return changeStr;
	}

	/**
	 * 转义页面元素 &quot; to \"
	 * 
	 * @param source
	 * @return String
	 */
	public static String ChangeHTML(String source) {
		String changeStr = source;
		// changeStr=source.replaceAll("&amp;","&");
		// changeStr=changeStr.replaceAll("&nbsp;"," ");
		// changeStr=changeStr.replaceAll("&lt;","<");
		// changeStr=changeStr.replaceAll("&gt;",">");
		// changeStr=changeStr.replaceAll("###","\r\n");
		changeStr = changeStr.replaceAll("&quot;", "\"");
		changeStr = changeStr.replaceAll("&#039;", "\'");
		//
		return changeStr;
	}

	public static Calendar TimeAdd(Calendar base, int hour) {
		base.add(Calendar.HOUR_OF_DAY, hour);
		return base;
	}

	/**
	 * 计算增加天数后的日期
	 * 
	 * @param c
	 * @param day
	 * @return
	 */
	public static Calendar addDate(Calendar c, long day) {

		long time = c.getTimeInMillis();
		day = day * 24 * 60 * 60 * 1000;
		time += day;
		Date d = new Date(time);
		Calendar c1 = Calendar.getInstance();
		c1.setTime(d);
		return c1;

	}

	/**
	 * 计算减少天数后的日期
	 * 
	 * @param c
	 * @param day
	 * @return
	 */
	public static Calendar subDate(Calendar c, long day) {

		long time = c.getTimeInMillis();
		day = day * 24 * 60 * 60 * 1000;
		time -= day;
		Date d = new Date(time);
		Calendar c1 = Calendar.getInstance();
		c1.setTime(d);
		return c1;

	}

	/**
	 * date转换成calendar
	 * 
	 * @param date
	 * @return
	 */
	public static Calendar convertDateToCalendar(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		return calendar;
	}

	/**
	 * 得到两个时间相隔的天数(c_end-c_beg)得到的天数<br/>
	 * 结束时间如果小于开始时间，则天数为0
	 * 
	 * @param c_beg
	 * @param c_end
	 * @return
	 */
	public static int getTimeInterval(Calendar c_beg, Calendar c_end) {
		long beg_time = c_beg.getTimeInMillis();// 开始时间
		long end_time = c_end.getTimeInMillis();// 结束时间
		long time = end_time - beg_time;
		if (time < 0)
			time = 0;
		int day = (int) (time / 1000 / 60 / 60 / 24);
		return day;
	}

	/**
	 * 得到当前月的第一天
	 * 
	 * @param calendar
	 * @return
	 */
	public static String getFirstDate(Calendar cal) {
		SimpleDateFormat datef = new SimpleDateFormat("yyyy-MM-dd");
		// 当前月的第一天
		cal.set(GregorianCalendar.DAY_OF_MONTH, 1);
		Date beginTime = cal.getTime();
		String beginTime1 = datef.format(beginTime)+" 00:00:00";
		return beginTime1;
	}


	/**
	 * 得到当前月的最后一天
	 * @param calendar
	 * @return
	 */
	public static String getLastDate(Calendar cal) {
		SimpleDateFormat datef = new SimpleDateFormat("yyyy-MM-dd");
		// 当前月的最后一天
		cal.set(Calendar.DATE, 1);
		cal.roll(Calendar.DATE, -1);
		Date endTime = cal.getTime();
		String endTime1 = datef.format(endTime)+" 23:59:59";
		return endTime1;
	}
	/**
	 * 获取星期第一天
	 * @param c
	 * @return
	 */
	public static String getFirstDateOfWeek(Calendar c,String pattern){
		SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
		c.setFirstDayOfWeek(Calendar.MONDAY);
		c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek()); // Monday
		return dateFormat.format(c.getTime());
	}
	/**
	 * 获取星期最后一天
	 * @param c
	 * @return
	 */
	public static String getLastDateOfWeek(Calendar c,String pattern){
		SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
		c.setFirstDayOfWeek(Calendar.MONDAY);
		c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6); // Sunday 
		return dateFormat.format(c.getTime());
	}
	/**
	 * 获取上星期第一天
	 * @return
	 */
	public static String getFirstDayOfLastWeek(Calendar c,String pattern){
		SimpleDateFormat sdf=new SimpleDateFormat(pattern);
        int day_of_week = c.get(Calendar.DAY_OF_WEEK) - 1;
        if (day_of_week == 0)
               day_of_week = 7;
        c.add(Calendar.WEEK_OF_MONTH, -1); //idx 参数，0为当前，1为下周 -1为上周以此类推      
        c.add(Calendar.DATE, -day_of_week + 1);
          return  sdf.format(c.getTime());//周一
	}
	/**
	 * 获取上星期最后一天
	 * @return
	 */
	public static String getLastDayOfLastWeek(Calendar c,String pattern){
		SimpleDateFormat sdf=new SimpleDateFormat(pattern);
		 int day_of_week = c.get(Calendar.DAY_OF_WEEK) - 1;
	        if (day_of_week == 0)
	               day_of_week = 7;
	        c.add(Calendar.WEEK_OF_MONTH, -1); //idx 参数，0为当前，1为下周 -1为上周以此类推      
	        c.add(Calendar.DATE, -day_of_week + 1);
	        c.add(Calendar.DATE, +6);
		return sdf.format(c.getTime());
	}
/*	public static void main(String arfs[]){
		System.out.println("上周星期一----------"+getFirstDayOfLastWeek(Calendar.getInstance(),"yyyy-MM-dd 00:00:00"));
		System.out.println("上周星期天----------"+getLastDayOfLastWeek(Calendar.getInstance(),"yyyy-MM-dd 23:59:59"));
	    System.out.println("本周星期一"+getFirstDateOfWeek(Calendar.getInstance(),"yyyy-MM-dd 00:00:00"));
		System.out.println("本周星期天"+getLastDateOfWeek(Calendar.getInstance(),"yyyy-MM-dd HH:mm:ss"));
		
		String res;
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		Calendar cl = Calendar.getInstance();
		            int day_of_week = cl.get(Calendar.DAY_OF_WEEK) - 1;
		            if (day_of_week == 0)
		                   day_of_week = 7;
		            cl.add(Calendar.WEEK_OF_MONTH, -1); //idx 参数，0为当前，1为下周 -1为上周以此类推      
		            cl.add(Calendar.DATE, -day_of_week + 1);
		              res = sdf.format(cl.getTime());//周一
		              cl.add(Calendar.DATE, +6);
		              res = res +"|"+sdf.format(cl.getTime());//周日 
		              

	}*/
	public static String getRandomString(int length) {
		String WORDS="0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();		
		for (int i = 0; i < length; i++) {
			sb.append(WORDS.charAt(random.nextInt(WORDS.length())));
		}
		return sb.toString();
	}
	
	/**
	 * 将毫秒转化成天时分秒
	 * @param ms
	 * @return
	 */
    public static String millisecondToStr(long millisecond) {
	    if (millisecond <= 0)
	    	return millisecond + "毫秒";
	    if (millisecond < 1000)
	    	return "1秒";
	    long second = millisecond / 1000;
	    String result = "";
	    long day = second / (3600 * 24);
	    if (day > 0)
	    	result += (day + "天");
	    second %= 3600 * 24;
	    long hour = second / 3600;
	    if (hour > 0)
	    	result += (hour + "小时");
	    second %= 3600;
	    long minute = second / 60;
	    if (minute > 0)
	    	result += (minute + "分钟");
	    second %= 60;
	    if (second > 0)
	    	result += (second + "秒");
	    return result;
    }
    
    /**
     * 将一个字符转化为大写
     * @param c
     * @return
     */
    public static char toUpper(char c){
    	if(isLetter(c))
    		return (char)(c & 0xDF);
    	else
    		return c;
    }
    
    /**
     * 将一个字符转化为小写
     * @param c
     * @return
     */
    public static char toLower(char c){
    	if(isLetter(c))
    		return (char)(c | 0x20);
    	else
    		return c;
    }
    
    /**
     * 将字符串转化为大写<br/>
     * 此方法经过本人测试：<br/>
     * 循环10000次时，JavaAPI提供的方法用时仅9毫秒，而此方法用时279毫秒<br/>
     * 当循环1亿次时，JavaAPI提供的方法用时61510毫秒，而此方法用时51975毫秒<br/>
     * 经过本人分析，这是因为调用方法时，java虚拟机会先去找自身的API，没有找到，才会到项目目录下去找<br/>
     * 所以当调用我自己的方法时，就会比javaAPI慢，但循环次数足够大时，这种差距就会缩小，并最终追上来<br/>
     * 因此，综上所述：此方法效率比javaAPI本身提供的方法效率高
     * @param str
     * @return
     */
    public static String toUpperString(String str){
    	if(null == str){
    		throw new NullPointerException("string is null");
    	}
    	int length = str.length();
    	StringBuilder sb = new StringBuilder("");
    	for (int i = 0; i < length; i++) {
			sb.append(toUpper(str.charAt(i)));
		}
    	return sb.toString();
    }
    
    /**
     * 将字符串转化为小写
     * 此方法经过本人测试：<br/>
     * 循环10000次时，JavaAPI提供的方法用时仅9毫秒，而此方法用时279毫秒<br/>
     * 当循环1亿次时，JavaAPI提供的方法用时61510毫秒，而此方法用时51975毫秒<br/>
     * 经过本人分析，这是因为调用方法时，java虚拟机会先去找自身的API，没有找到，才会到项目目录下去找<br/>
     * 所以当调用我自己的方法时，就会比javaAPI慢，但循环次数足够大时，这种差距就会缩小，并最终追上来<br/>
     * 因此，综上所述：此方法效率比javaAPI本身提供的方法效率高
     * @param str
     * @return
     */
    public static String toLowerString(String str){
    	if(null == str){
    		throw new NullPointerException("string is null");
    	}
    	int length = str.length();
    	StringBuilder sb = new StringBuilder("");
    	for (int i = 0; i < length; i++) {
			sb.append(toLower(str.charAt(i)));
		}
    	return sb.toString();
    }
    
    /**
     * 判断是否为字母
     * @param c
     * @return
     */
    public static boolean isLetter(char c){
    	if((c >=65 && c<= 90) || (c>=97 && c<=122)){
    		return true;
    	}
    	return false;
    }
      public static boolean isNumeric(String str){
    	if(null != str && !"".equals(str.trim()) && str.matches("[0-9]+") ){
    		return true;
    	}
    	return false;
    }
    //如果为true,则为小数，否则为整数
    public static boolean isNumeric(String str,boolean flag){
    	if(null == str || "".equals(str.trim())){
    		return false;
    	}
    	if(flag){
    		if(str.matches("[0-9]+.[0-9]+")){
    			return true;
    		}
    	}else{
    		if(str.matches("[0-9]+") ){
        		return true;
        	}
    	}
    	
    	return false;
    }
    /**
     * 判断是否为中文
     * @param c
     * @return
     */
    public static boolean isChinese(char c) {
    	Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);    
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS    
            || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS    
            || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A    
            || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION    
            || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION    
            || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {    
          return true;    
        }    
        return false;
    }
    /**
     * 判断是否为中文乱码
     * @param strName
     * @return
     */
    public static boolean isMessyCode(String strName) {    
        Pattern p = Pattern.compile("\\s*|\t*|\r*|\n*");    
        Matcher m = p.matcher(strName);    
        String after = m.replaceAll("");    
        String temp = after.replaceAll("}", "");    
        char[] ch = temp.trim().toCharArray();    
        float chLength = ch.length;    
        float count = 0;    
        for (int i = 0; i < ch.length; i++) {    
          char c = ch[i];    
          if (!Character.isLetterOrDigit(c)) {    
        
            if (!isChinese(c)) {    
              count = count + 1;      
            }    
          }    
        }    
        float result = count / chLength;    
        if (result > 0.4) {    
          return true;    
        } else {    
          return false;    
        }    
        
      }    
    	
    
    public  static String repleceTrim(String s){
    	String msg="";
    	if(s!=null&&!"".equals(s.trim())&&s.indexOf("\r")!=-1){
    		msg=s.replace("\r", "");
    	}
    	return msg;
    }
}
